package nio.file;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * FileDeleteDemo
 *
 * @author chenxin
 * @date 2022/05/16 17:39
 **/
public class FileDeleteDemo {

    public static void main(String[] args) throws IOException {

        Files.walkFileTree(Paths.get("E:\\Cache"),new SimpleFileVisitor<Path>(){

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 遍历文件时 删除文件
                Files.delete(file);
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return super.visitFileFailed(file, exc);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // 离开文件夹时 删除文件夹（必须先删除文件夹中所有文件）
                Files.delete(dir);
                return super.postVisitDirectory(dir, exc);
            }
        });

    }


}